package com.myproject.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myproject.entity.User;
import com.myproject.enums.ErrorCode;
import com.myproject.exception.BusinessException;
import com.myproject.mapper.UserMapper;
import com.myproject.service.UserService;
import com.myproject.utils.JwtUtils;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private JwtUtils jwtUtils;

	/**
	 * 根据用户名加载用户详情
	 * 
	 * @param username 用户名
	 * @return UserDetails 用户详情
	 * @throws UsernameNotFoundException 当用户不存在时抛出
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
		if (user == null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		return user;
	}

	/**
	 * 用户注册
	 * 
	 * @param user 用户对象，包含用户名和密码等信息
	 * @throws BusinessException 当用户名已存在时抛出USER_EXIST错误
	 */
	@Override
	public void register(User user) throws BusinessException {
		// 检查用户名是否已存在
		if (userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername())) != null) {
			throw new BusinessException(ErrorCode.USER_EXIST);
		}

		// 密码加密
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		userMapper.insert(user);
	}

	/**
	 * 用户登录
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @return String 生成的JWT令牌
	 * @throws BusinessException 当用户不存在时抛出USER_NOT_EXIST错误， 当密码错误时抛出PASSWORD_ERROR错误
	 */
	@Override
	public String login(String username, String password) throws BusinessException {
		User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
		if (user == null) {
			throw new BusinessException(ErrorCode.USER_NOT_EXIST);
		}

		// 验证密码
		if (!passwordEncoder.matches(password, user.getPassword())) {
			throw new BusinessException(ErrorCode.PASSWORD_ERROR);
		}

		// 生成JWT令牌
		return jwtUtils.generateToken(username);
	}

	/**
	 * 更新用户信息
	 * 
	 * @param user 用户对象，必须包含有效的用户ID
	 * @throws BusinessException 当用户ID为空时抛出PARAM_ERROR错误
	 */
	@Override
	public void updateUser(User user) throws BusinessException {
		if (user.getId() == null) {
			throw new BusinessException(ErrorCode.PARAM_ERROR, "用户ID不能为空");
		}
		userMapper.updateById(user);
	}

	/**
	 * 修改用户密码
	 * 
	 * @param userId      用户ID
	 * @param oldPassword 旧密码（明文）
	 * @param newPassword 新密码（明文）
	 * @throws BusinessException 当用户不存在时抛出USER_NOT_EXIST错误，
	 *                           当旧密码不匹配时抛出PASSWORD_ERROR错误
	 */
	@Override
	public void changePassword(Long userId, String oldPassword, String newPassword) throws BusinessException {
		User user = userMapper.selectById(userId);
		if (user == null) {
			throw new BusinessException(ErrorCode.USER_NOT_EXIST);
		}

		if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
			throw new BusinessException(ErrorCode.PASSWORD_ERROR);
		}

		user.setPassword(passwordEncoder.encode(newPassword));
		userMapper.updateById(user);
	}

	/**
	 * 删除用户
	 * 
	 * @param userId 要删除的用户ID
	 * @throws BusinessException 当用户不存在时抛出USER_NOT_EXIST错误
	 */
	@Override
	public void deleteUser(Long userId) throws BusinessException {
		if (userMapper.selectById(userId) == null) {
			throw new BusinessException(ErrorCode.USER_NOT_EXIST);
		}
		userMapper.deleteById(userId);
	}

	/**
	 * 根据ID获取用户信息
	 * 
	 * @param userId 用户ID
	 * @return User 用户对象
	 * @throws BusinessException 当用户不存在时抛出USER_NOT_EXIST错误
	 */
	@Override
	public User getUserById(Long userId) throws BusinessException {
		User user = userMapper.selectById(userId);
		if (user == null) {
			throw new BusinessException(ErrorCode.USER_NOT_EXIST);
		}
		return user;
	}

	/**
	 * 获取用户分页列表
	 * 
	 * @param page 页码，从0开始
	 * @param size 每页大小
	 * @return 分页用户列表
	 */
	@Override
	public Page<User> getUserList(int page, int size) {
		// 创建分页请求
		PageRequest pageRequest = PageRequest.of(page, size);

		// 执行分页查询
		com.baomidou.mybatisplus.extension.plugins.pagination.Page<User> mpPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
				page + 1, size);
		userMapper.selectPage(mpPage, null);

		// 转换为Spring Data Page
		return new PageImpl<>(mpPage.getRecords(), pageRequest, mpPage.getTotal());
	}
}